package com.filldream.fastboot.web.config.request;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求过滤器，替换HttpServletRequest
 * 过滤器会执行两遍doFilter，请求一次，返回一次，第二次的getContentType为null
 * @author RickSun
 * @data 2023-12-08 10:11
 */
@Slf4j
@Component
public class RequestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        //是JSON的才转换RequestWrapper
        if( MediaType.APPLICATION_JSON_VALUE.equals(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType) ){
            ServletRequest requestWrapper = new RequestWrapper((HttpServletRequest) request);
            chain.doFilter(requestWrapper, response);
        }else{
            chain.doFilter( request,response );
        }
    }

}

